사이트 내 전체검색
Cocos2d 멀티터치를 활용해서 총알 발사와 이동을 동시에 처리하기
로빈아빠
https://cmd.kr/iphone/53 URL이 복사되었습니다.

본문

방향키 터치를 해서 이동을 함과 동시에 총알 발사를 위한 터치를 처리하려면 어떻게 하면 좋을까?
터치를 이용한 이동은 방향키 터치가 지속되는 동안 계속된다는 것을 가정한다.
예를 들어 왼손으로 오른쪽 방향키를 계속 누르고 있으면 계속해서 오른쪽으로 이동하는 것이다.
이 때 총알 발사를 위해 터치를 할 경우 두 개의 터치를 독립적으로 식별할 수 있는 방법이 있을까?


총알 발사는 초록색 사각형을 중심으로 터치된 좌표의 방향으로 총알이 발사된다.
즉, 이동과 동시에 총알 발사가 이루어 져야 한다.

결론 부터 말하자면 가능하다.
iOS에서는 멀티 터치에서 각각의 터치를 시작부터 종료(TouchBegan -> TouchMove -> TouchEnd)까지 식별할 수 있는 방법을 제공하는데 UITouch 가 그것이다.

소스코드는 다음과 같다.
- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {	
    NSLog(@"Touches Began");	
	
	UITouch *touch = [touches anyObject];
	NSLog(@"%08x", touch);
    CGPoint location = [touch locationInView: [touch view]];
    location = [[CCDirector sharedDirector] convertToGL:location];
	NSLog(@"location = %f %f", location.x, location.y);
	
	SEL sel = [self findCtlSelector:location];

	if (sel != nil) {
		_ctlTouch = touch;
		_timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:sel userInfo:nil repeats:YES];
	} else {
		[self fireProjectileTo:location];
	}
	
}

- (void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
	UITouch *touch = [touches anyObject];
	
	// 방향키가 아니면 루틴 종료
	if (touch != _ctlTouch) {
		return;
	}
	
	// 방향키 지속 타이머 해제
	if (_timer != nil) {
		[_timer invalidate];
		_timer = nil;
	}
	
    CGPoint location = [touch locationInView: [touch view]];
    location = [[CCDirector sharedDirector] convertToGL:location];

	SEL sel = [self findCtlSelector:location];
	
	// 방향키를 벗어날 경우
	if (sel == nil) {
		//_ctlTouch = nil;
		return;
	}
		
	// 새로운 방향으로 움직이기 시작
	_ctlTouch = touch;
	_timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:sel userInfo:nil repeats:YES];
}

- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    NSLog(@"Touches Ended");
	
	UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInView: [touch view]];
    location = [[CCDirector sharedDirector] convertToGL:location];
	NSLog(@"location = %f %f", location.x, location.y);
	
	
	if (touch == _ctlTouch && _timer != nil) 
	{
		[_timer invalidate];
		_timer = nil;
		_ctlTouch = nil;
	}
}

댓글목록

등록된 댓글이 없습니다.

Search

Copyright © Cmd 명령어 18.217.182.45